package com.sx.pipeline.ui.setting

import android.util.Log
import android.view.View
import com.alibaba.android.arouter.facade.Postcard
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.facade.callback.NavCallback
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.cretin.www.cretinautoupdatelibrary.interfaces.AppDownloadListener
import com.cretin.www.cretinautoupdatelibrary.model.DownloadInfo
import com.cretin.www.cretinautoupdatelibrary.model.TypeConfig
import com.cretin.www.cretinautoupdatelibrary.utils.AppUpdateUtils
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.interfaces.OnConfirmListener
import com.lxj.xpopup.interfaces.OnInputConfirmListener
import com.sx.mvvmlibs.app.AppActivityManager
import com.sx.mvvmlibs.utils.Logs
import com.sx.pipeline.BR
import com.sx.pipeline.R
import com.sx.pipeline.app.base.CYDataBindingBaseActivity
import com.sx.pipeline.app.config.IdentityType
import com.sx.pipeline.arouth.RouteManager
import com.sx.pipeline.arouth.RoutePath
import com.sx.pipeline.databinding.ActSettingBinding
import com.sx.pipeline.repos.http.res.VersionUpdateVO
import com.sx.pipeline.ui.LaunchActivity
import com.sx.pipeline.ui.mine.MineVM
import com.sx.pipeline.ui.task.ReleaseTaskVM
import com.sx.pipeline.utils.AndroidUtil
import com.sx.pipeline.utils.CacheDataManager
import io.rong.imkit.RongIM


/**
 * @Author: YY
 * @Date: 2022/4/5
 * @Description: 设置
 */
@Route(path = RoutePath.Setting.SETTING)
class SettingActivity :
    CYDataBindingBaseActivity<ActSettingBinding, MineVM>(
        R.layout.act_setting
    ), View.OnClickListener {

    override fun initData() {
        mBinding.setVariable(BR.onClick, this)
        //获取系统缓存
        mBinding.sbCache.rightText = CacheDataManager.getTotalCacheSize(this)
        //获取系统版本号
        mBinding.sbVersion.rightText = AndroidUtil.getVersionName(this)
        mBinding.titleBar.leftView.setOnClickListener {
            finish()
        }
    }

    override fun initViewObservable() {
        super.initViewObservable()
        //监听版本更新
        observe(mViewModel.appVersionEvent) {
            if (it!!.version > AndroidUtil.getAppVersionCode(this)) {
                initUpdate(it)
            }else{
                ToastUtils.showLong("当前已是最新版本")
            }
        }

    }

    override fun initIdentity(type: Int) {
        Logs.d("res" + mViewModel.mModel.getToken())
        super.initIdentity(type)
        Logs.d("initIdentity $type")
        when (type) {
            IdentityType.OPERATING_UNIT.code -> {
                // 运营单位
                mBinding.sbResetPay.visibility = View.GONE
                mBinding.sbBank.visibility = View.GONE
            }
            IdentityType.BUILD_UNIT.code -> {
                // 施工单位
                mBinding.sbResetPay.visibility = View.VISIBLE
                mBinding.sbBank.visibility = View.VISIBLE
            }
            IdentityType.SUPPLIER.code -> {
                // 供应商
                mBinding.sbResetPay.visibility = View.VISIBLE
                mBinding.sbBank.visibility = View.VISIBLE
            }
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            //个人资料
            R.id.sb_personal_info -> {
                ARouter.getInstance().build(RoutePath.Setting.PROFILE).navigation()
            }
            //关于我们
            R.id.sb_about -> {
                ARouter.getInstance().build(RoutePath.Setting.ABOUT).navigation()
            }
            //修改登录密码
            R.id.sb_reset_pass -> ARouter.getInstance().build(RoutePath.Setting.MODIFY_LOGIN_PASS)
                .withInt("type", 0).navigation()
            //修改支付密码
            R.id.sb_reset_pay -> {
                ARouter.getInstance().build(RoutePath.Setting.MODIFY_LOGIN_PASS).withInt("type", 1)
                    .navigation()
            }
            R.id.sb_bank -> {
                ARouter.getInstance().build(RoutePath.Wallet.BANK_CARD).navigation()
            }
            R.id.sb_version -> {
                //获取app版本信息接口
                mViewModel.getAppVersion()
            }
            //退出登录
            R.id.tv_sign_out -> {
                XPopup.Builder(this)
                    .isDestroyOnDismiss(true)
                    .asConfirm(
                        getString(R.string.hint), getString(R.string.q_signout_account),
                        getString(R.string.cancel), getString(R.string.confirm),
                        {
                            mViewModel.mModel.clearToken()
                            RouteManager.Login.intentToLogin(this, object : NavCallback() {
                                override fun onArrival(postcard: Postcard?) {
                                    CacheDataManager.clearAllCache(this@SettingActivity)
                                    RongIM.getInstance().logout();//融云断开连接
                                    ActivityUtils.finishAllActivities()
                                }
                            })
                        }, null, false
                    ).show()
            }
            //注销账号
            R.id.tv_logout -> {
                XPopup.Builder(this)
                    .isDestroyOnDismiss(true)
                    .asConfirm(
                        getString(R.string.hint), getString(R.string.q_logout_account),
                        getString(R.string.cancel), getString(R.string.confirm),
                        {
                            mViewModel.cancelAccount()
                        }, null, false
                    ).show()
            }
            //清除缓存
            R.id.sb_cache -> {
                XPopup.Builder(this)
                    .isDestroyOnDismiss(true)
                    .asConfirm(
                        getString(R.string.hint), getString(R.string.txt_clear_cache_tips),
                        getString(R.string.cancel), getString(R.string.confirm),
                        {
                            CacheDataManager.clearAllCache(this)
                            ToastUtils.showShort("清除完成~")
                            mBinding.sbCache.rightText = CacheDataManager.getTotalCacheSize(this)
                        }, null, false
                    ).show()

            }
            //切换服务器
            R.id.sb_server ->{
                //切换服务器
                XPopup.Builder(this)
                    .asInputConfirm("切换服务器","",SPUtils.getInstance().getString("baseUrl","http://api.gxtapp.com"),"",object :OnInputConfirmListener{
                        override fun onConfirm(text: String?) {
                            SPUtils.getInstance().put("baseUrl",text)
                            restartApp()
                        }
                    }).show()
            }
        }
    }

    fun initUpdate(data: VersionUpdateVO) {
        DownloadInfo().setApkUrl(data.downloadUrl)
            .setFileSize(31338250)
            .setProdVersionCode(data.version)
            .setProdVersionName(data.versionName)
            .setMd5Check("7C9661B6FB3D1BCBCBCDF318A3B3E375")
            .setForceUpdateFlag(if (data.forceUpdate) 0 else 1)
            .setUpdateLog(data.remark)
        AppUpdateUtils.getInstance().updateConfig.uiThemeType = TypeConfig.UI_THEME_CUSTOM
        //打开文件MD5校验
//        AppUpdateUtils.getInstance().updateConfig.isNeedFileMD5Check = true
//        AppUpdateUtils.getInstance().updateConfig.dataSourceType = TypeConfig.DATA_SOURCE_TYPE_MODEL
//        //开启或者关闭后台静默下载功能
//        AppUpdateUtils.getInstance().updateConfig.isAutoDownloadBackground =
//            listModel.isAutoUpdateBackground()
//        if (listModel.isAutoUpdateBackground()) {
//            //开启静默下载的时候推荐关闭通知栏进度提示
//            AppUpdateUtils.getInstance().updateConfig.isShowNotification = false
//        } else {
//            AppUpdateUtils.getInstance().updateConfig.isShowNotification = true
//        }
        //因为这里打开了MD5的校验 我在这里添加一个MD5检验监听监听
        AppUpdateUtils.getInstance()
            .addAppUpdateInfoListener { isLatest -> Log.e("HHHHHHHHHHHHHHH", "isLatest:$isLatest") }
            .addAppDownloadListener(object : AppDownloadListener {
                override fun downloading(progress: Int) {
                    Log.e("HHHHHHHHHHHHHHH", "progress:$progress")
                }

                override fun downloadFail(msg: String) {
                    Log.e("HHHHHHHHHHHHHHH", "msg:$msg")
                }

                override fun downloadComplete(path: String) {
                    Log.e("HHHHHHHHHHHHHHH", "path:$path")
                }

                override fun downloadStart() {
                    Log.e("HHHHHHHHHHHHHHH", "start")
                }

                override fun reDownload() {}
                override fun pause() {}
            })
            .checkUpdate()
    }

    fun restartApp(){
        XPopup.Builder(this).asConfirm("提示","重启APP即可生效",object : OnConfirmListener {
            override fun onConfirm() {
                System.exit(0)
            }
        }).show()


    }

}